import { html, PageComponent /* reactive */ } from 'nvagir'
import './Login.less'

/**
 * @template LoginData save Login information
 */
type LoginData = {
  user: string
  password: string
}

const Login: PageComponent = () => {
  /**
   * Storage example for user and password
   */
  const data: LoginData = {
    user: 'admin',
    password: '123456',
  }

  /**
   * This is for submit login information
   */
  const handlerConfirm: EventListener = ev => {
    ev.preventDefault()
    if (flag.f1 == true && flag.f2 == true) {
      let username = (<HTMLInputElement>document.querySelector('.user')).value
      let password = (<HTMLInputElement>document.querySelector('.user-pass'))
        .value
      console.log('username', username!)
      console.log('password', password!)
      alert('Logged in successfully!')
      history.nvagirRouter.push('/playGround')
    } else {
      alert('Input error! Please check again.')
    }
  }

  /*
   * Get username, password and save it in the formData
   */
  const { el } = html`
    <div class="login-page">
      <div class="form">
        <form class="login-form" n@submit=${handlerConfirm}>
          <input
            name="user"
            n@input=${ev => check(ev.target! as HTMLInputElement, data.user)}
            type="text"
            placeholder="username"
            class="user"
          />
          <input
            name="password"
            type="password"
            placeholder="password"
            class="user-pass"
            n@input=${ev =>
              check(ev.target! as HTMLInputElement, data.password)}
          />
          <button n@click=${handlerConfirm}>login</button>
          <p class="message">
            Not registered?
            <a href="#" n@click=${() => history.nvagirRouter.push('/register')}
              >Create an account</a
            >
          </p>
        </form>
      </div>
    </div>
  `

  return { el }
}
export default Login
/**
 * Used flag.xx to determine whether the
 * login information is correct
 * @param flag.f1 determine name Format
 * @param flag.f2 determine password Format
 */
let flag = {
  f1: false,
  f2: false,
}

/**
 * This is for verify login information
 * @param ele Entered word
 * @param origin original data
 */
function check(ele: any, origin: any): void {
  if (origin == ele.value) {
    console.log(ele.value)
    console.log('right')
    ele.style.border = 'none'
    switch (ele.name) {
      case 'user':
        flag.f1 = true
      case 'password':
        flag.f2 = true
    }
  } else {
    console.log('error')
    ele.style.border = '1px solid #EF3B3A'
    switch (ele.name) {
      case 'user':
        flag.f1 = false
      case 'password':
        flag.f2 = false
    }
  }
}
